#! /usr/local/bin/php
<?php

/* PHP Socket Server will relay GPSD response to a websocket */
 
require_once('websocket.php');

class echo_server extends WebSocketServer 
{
    //protected $maxBufferSize = 1048576; //1MB... overkill for an echo server, but potentially plausible for other applications
    protected function process ($user, $message) {
		$resp2 = "";
		$resp = @fread($this->socketGPS, 5000); # SKY can be pretty big
		if (preg_match('/{"class":"TPV".+}/i', $resp, $m)){
				$resp = $m[0];
		}
		$resp2 .= $resp;
		$this->send($user, $resp2);
    }
     
    protected function connected ($user) {
		// connect to gpsd
		$gpsdIP = '127.0.0.1';
		$gpsdPort = '2947';
		
		$this->socketGPS = @fsockopen($gpsdIP, $gpsdPort, $errno, $errstr, 2);
		@fwrite($this->socketGPS, "?WATCH={\"enable\":true, \"json\":true}\n");
		usleep(900);
		echo "Connected to GPSD\n";
    }
     
    protected function closed ($user) {
		@fwrite($this->socketGPS, "?WATCH={\"enable\":false}\n");
		@fclose($this->socketGPS);
        echo "User closed connection\n";
    }

}

// Create a new websocket for GPSD output
$host = '127.0.0.1';
$port = 9000;
 
$server = new echo_server($host , $port );

try {
  $server->run();
}
catch (Exception $e) {
  $server->stdout($e->getMessage());
}



?>
